package handlers

import (
	"encoding/json"
	"log/slog"

	"lsp-server/internal/protocol"
)

const HoverMethod = "textDocument/hover"

type Hover struct {
	fileURIToContents *map[string][]string
}

func NewHover(fileURIToContents *map[string][]string) *Hover {
	return &Hover{fileURIToContents: fileURIToContents}
}

func (h Hover) Call(params json.RawMessage) (any, error) {
	slog.Info("received hover method")
	hParams, err := h.parseParams(params)
	if err != nil {
		slog.Error("Error to parse hover params")
		return nil, err
	}
	slog.Debug("hover params", slog.Any("params", *hParams))

	hoverItem := h.createHoverItem(hParams)

	return hoverItem, nil
}

func (h Hover) createHoverItem(hParams *protocol.HoverParams) *protocol.Hover {
	hoverItem := &protocol.Hover{
		Contents: protocol.MarkupContent{
			Kind:  protocol.Markdown,
			Value: "some hover",
		},
		Range: protocol.Range{
			Start: protocol.Position{
				Line:      hParams.Position.Line,
				Character: hParams.Position.Character,
			},
			End: protocol.Position{
				Line:      hParams.Position.Line,
				Character: hParams.Position.Character,
			},
		},
	}
	return hoverItem
}

func (h Hover) parseParams(params json.RawMessage) (*protocol.HoverParams, error) {
	var hoverParams protocol.HoverParams
	if err := json.Unmarshal(params, &hoverParams); err != nil {
		return nil, err
	}

	return &hoverParams, nil
}
